import { useState, useContext, useEffect } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import { AuthContext } from '@/contexts/authContext';
import { ThemeContext } from '@/App';
import { Toaster, toast } from 'sonner';
import { 
  Brain, 
  Sparkles, 
  Clock, 
  Heart, 
  Target, 
  Layers, 
  MessageSquare,
  CheckCircle,
  RefreshCw,
  ChevronLeft,
  Sun,
  Moon,
  AlertCircle
} from 'lucide-react';
import { 
  generateStoryWithLLM, 
  type StoryGenerationConfig, 
  type GeneratedStory,
  checkStoryUniqueness,
  preGenerateStoryImages
} from '@/lib/aiUtils';
// 导入故事生成相关函数
import ApiConfigModal from '@/components/ApiConfigModal';
import { getAiMode } from '@/lib/config';
import { getApiKey, hasValidApiKey } from '@/lib/apiKeyStore';

// 定义角色和主题的接口
interface Character {
  id: string;
  name: string;
  icon: string;
  traits?: string[];
}

interface Theme {
  id: string;
  name: string;
  icon: string;
  description: string;
}

// 定义场景、情感和道德寓意选项
interface StoryOption {
  id: string;
  name: string;
  icon: string;
}

export default function GeneratePage() {
  const { isAuthenticated } = useContext(AuthContext);
  const { isDark, toggleDarkMode } = useContext(ThemeContext);
  const navigate = useNavigate();
  
  // 检查用户是否已认证，生成故事需要登录
  useEffect(() => {
    if (!isAuthenticated) {
      navigate('/login');
    }
  }, [isAuthenticated, navigate]);
  
  // 角色列表数据
  const characters: Character[] = [
    { id: '1', name: '小狐狸', icon: '🦊', traits: ['聪明', '好奇', '勇敢'] },
    { id: '2', name: '小熊', icon: '🐻', traits: ['憨厚', '善良', '力气大'] },
    { id: '3', name: '小兔子', icon: '🐰', traits: ['活泼', '敏捷', '善良'] },
    { id: '4', name: '小海豚', icon: '🐬', traits: ['友好', '聪明', '喜欢探索'] },
    { id: '5', name: '小松鼠', icon: '🐿️', traits: ['机灵', '活泼', '善于储存'] },
    { id: '6', name: '猫头鹰', icon: '🦉', traits: ['智慧', '沉稳', '夜间活动'] },
    { id: '7', name: '小龙', icon: '🐉', traits: ['神奇', '会飞', '能喷火'] },
    { id: '8', name: '独角兽', icon: '🦄', traits: ['高贵', '神秘', '有治愈能力'] },
    { id: '9', name: '小熊猫', icon: '🐼', traits: ['可爱', '悠闲', '爱吃竹子'] },
    { id: '10', name: '小狮子', icon: '🦁', traits: ['勇敢', '领导力', '活泼'] },
    { id: '11', name: '小象', icon: '🐘', traits: ['温和', '强壮', '记忆力好'] },
    { id: '12', name: '小猴子', icon: '🐒', traits: ['调皮', '灵活', '聪明'] },
    { id: '13', name: '小公主', icon: '👸', traits: ['善良', '优雅', '勇敢'] },
    { id: '14', name: '小王子', icon: '🤴', traits: ['好奇', '善良', '有责任感'] },
    { id: '15', name: '小矮人', icon: '🧝‍♂️', traits: ['勤劳', '聪明', '团结'] },
    { id: '16', name: '小女侠', icon: '🦸‍♀️', traits: ['勇敢', '正义', '乐于助人'] },
    { id: '17', name: '小骑士', icon: '🦸‍♂️', traits: ['勇敢', '忠诚', '保护他人'] },
    { id: '18', name: '小仙女', icon: '🧚‍♀️', traits: ['善良', '有魔法', '轻盈'] },
    { id: '19', name: '小巫师', icon: '🧙‍♂️', traits: ['智慧', '神秘', '会魔法'] },
    { id: '20', name: '小魔女', icon: '🧙‍♀️', traits: ['调皮', '聪明', '会魔法'] },
    { id: '21', name: '小海盗', icon: '🏴‍☠️', traits: ['勇敢', '冒险', '自由'] },
    { id: '22', name: '小宇航员', icon: '👨‍🚀', traits: ['好奇', '勇敢', '聪明'] },
    { id: '23', name: '小侦探', icon: '🕵️‍♂️', traits: ['聪明', '细心', '善于推理'] },
    { id: '24', name: '小医生', icon: '👩‍⚕️', traits: ['善良', '细心', '乐于助人'] },
  ];
  
  // 主题列表数据
  const themes: Theme[] = [
    { id: '1', name: '冒险探索', icon: '📚', description: '充满未知的奇妙旅程' },
    { id: '2', name: '寻宝探险', icon: '💰', description: '寻找神秘宝藏的冒险' },
    { id: '3', name: '太空探索', icon: '🚀', description: '探索宇宙的星际旅行' },
    { id: '4', name: '海洋探险', icon: '🌊', description: '深海世界的奇妙发现' },
    { id: '5', name: '魔法奇幻', icon: '🔮', description: '神奇的魔法世界' },
    { id: '6', name: '童话仙境', icon: '🏰', description: '梦幻的童话世界' },
    { id: '7', name: '龙与魔法', icon: '🐉', description: '神奇的龙族传说' },
    { id: '8', name: '时空穿越', icon: '⏰', description: '穿越时空的奇妙冒险' },
    { id: '9', name: '友谊成长', icon: '👫', description: '珍贵的友谊故事' },
    { id: '10', name: '家庭温暖', icon: '🏠', description: '家人之间的温馨故事' },
    { id: '11', name: '团队合作', icon: '🤝', description: '团队协作的力量' },
    { id: '12', name: '善良友爱', icon: '💖', description: '传递爱心和善意' },
    { id: '13', name: '学习成长', icon: '🎒', description: '知识探索的乐趣' },
    { id: '14', name: '科学探索', icon: '🔬', description: '发现科学的奥秘' },
    { id: '15', name: '自然环保', icon: '🌳', description: '保护美丽的自然' },
    { id: '16', name: '音乐艺术', icon: '🎵', description: '感受音乐的魅力' },
    { id: '17', name: '勇气挑战', icon: '💪', description: '勇敢面对困难' },
    { id: '18', name: '梦想实现', icon: '🌟', description: '追逐梦想的旅程' },
  ];
  
  // 场景选项
  const settings: StoryOption[] = [
    { id: '1', name: '森林', icon: '🌳' },
    { id: '2', name: '海洋', icon: '🌊' },
    { id: '3', name: '太空', icon: '🚀' },
    { id: '4', name: '城堡', icon: '🏰' },
    { id: '5', name: '村庄', icon: '🏘️' },
    { id: '6', name: '沙漠', icon: '🏜️' },
    { id: '7', name: '雪山', icon: '🏔️' },
    { id: '8', name: '花园', icon: '🌷' },
  ];
  
  // 情感选项
  const emotions: StoryOption[] = [
    { id: '1', name: '快乐', icon: '😄' },
    { id: '2', name: '勇敢', icon: '💪' },
    { id: '3', name: '温暖', icon: '🌞' },
    { id: '4', name: '惊喜', icon: '😮' },
    { id: '5', name: '感动', icon: '🥺' },
    { id: '6', name: '冒险', icon: '⛵' },
    { id: '7', name: '神秘', icon: '🔮' },
    { id: '8', name: '奇幻', icon: '🧚' },
  ];
  
  // 道德寓意选项
  const morals: StoryOption[] = [
    { id: '1', name: '友谊珍贵', icon: '🤝' },
    { id: '2', name: '勇敢面对', icon: '💪' },
    { id: '3', name: '诚实善良', icon: '⭐' },
    { id: '4', name: '团结协作', icon: '👪' },
    { id: '5', name: '保护环境', icon: '🌍' },
    { id: '6', name: '坚持梦想', icon: '🌟' },
    { id: '7', name: '尊重他人', icon: '🙏' },
    { id: '8', name: '分享快乐', icon: '🎁' },
  ];
  
  // 故事长度选项
  const lengths = [
    { id: 'short', name: '短篇 (4页)' },
    { id: 'medium', name: '中篇 (7页)' },
    { id: 'long', name: '长篇 (10页)' },
  ];
  
  // 选中的故事元素状态
  const [selectedCharacter, setSelectedCharacter] = useState<Character | null>(null);
  const [selectedTheme, setSelectedTheme] = useState<Theme | null>(null);
  const [selectedSetting, setSelectedSetting] = useState<StoryOption | null>(null);
  const [selectedEmotion, setSelectedEmotion] = useState<StoryOption | null>(null);
  const [selectedMoral, setSelectedMoral] = useState<StoryOption | null>(null);
  const [selectedLength, setSelectedLength] = useState<'short' | 'medium' | 'long'>('medium');
  const [customPrompt, setCustomPrompt] = useState('');
  
  // 生成状态
   const [isGenerating, setIsGenerating] = useState(false);
  const [generatedStory, setGeneratedStory] = useState<GeneratedStory | null>(null);
  const [aiProcessStep, setAiProcessStep] = useState<string>('');
  const [uniquenessScore, setUniquenessScore] = useState<number | null>(null);
  
  // AI智能提示
  const [aiSuggestions, setAISuggestions] = useState<string[]>([]);
  const [isLoadingSuggestions, setIsLoadingSuggestions] = useState(false);
  
  // API配置模态框状态
  const [isApiConfigOpen, setIsApiConfigOpen] = useState(false);
  const [aiMode, setAiMode] = useState<'real' | 'mock'>('mock');
  
  // 检查用户是否已认证
  useEffect(() => {
    if (!isAuthenticated) {
      navigate('/login');
    } else {
      // 初始化AI模式
      setAiMode(getAiMode());
    }
  }, [isAuthenticated, navigate]);
  
  // 从URL参数中预选择
  useEffect(() => {
    const urlParams = new URLSearchParams(window.location.search);
    const preselectParam = urlParams.get('preselect');
    
    if (preselectParam) {
      const [type, value] = preselectParam.split('=');
      const decodedValue = decodeURIComponent(value);
      
      if (type === 'character') {
        const character = characters.find(c => c.name === decodedValue);
        if (character) {
          setSelectedCharacter(character);
        }
      } else if (type === 'theme') {
        const theme = themes.find(t => t.name === decodedValue);
        if (theme) {
          setSelectedTheme(theme);
        }
      }
    }
  }, []);
  
  // 当选择变化时生成AI建议
  useEffect(() => {
    if ((selectedCharacter || selectedTheme || selectedSetting) && !isGenerating) {
      generateAISuggestions();
    }
  }, [selectedCharacter, selectedTheme, selectedSetting, isGenerating]);
  
  // 生成AI建议
  const generateAISuggestions = async () => {
    setIsLoadingSuggestions(true);
    
    // 模拟AI思考过程
    setTimeout(() => {
      const suggestions: string[] = [];
      
      if (selectedCharacter && !selectedTheme) {
        // 基于角色推荐主题
        const characterThemes: Record<string, string[]> = {
          '小狐狸': ['星空冒险', '寻宝探险', '森林奇遇'],
          '小熊': ['魔法森林', '友谊成长', '家庭温暖'],
          '小兔子': ['彩虹桥的约定', '勇气挑战', '梦想实现'],
          '小海豚': ['海底寻宝', '海洋探险', '友谊之旅'],
          '小松鼠': ['森林冒险', '储存食物大作战', '结交新朋友']
        };
        
        const recommendedThemes = characterThemes[selectedCharacter.name] || ['冒险探索', '友谊成长', '梦想实现'];
        suggestions.push(`推荐主题: ${recommendedThemes.join('、')}`);
      }
      
      if (selectedTheme && !selectedCharacter) {
        // 基于主题推荐角色
        const themeCharacters: Record<string, string[]> = {
          '星空冒险': ['小狐狸', '小王子', '小宇航员'],
          '魔法森林': ['小熊', '小精灵', '小巫师'],
          '友谊成长': ['小兔子', '小松鼠', '小猴子'],
          '海底寻宝': ['小海豚', '小海龟', '小美人鱼'],
          '勇敢挑战': ['小狮子', '小骑士', '小女侠']
        };
        
        const recommendedCharacters = themeCharacters[selectedTheme.name] || ['小狐狸', '小熊', '小兔子'];
        suggestions.push(`推荐角色: ${recommendedCharacters.join('、')}`);
      }
      
      if (selectedCharacter && selectedTheme) {
        // 推荐场景和情感
        const settingSuggestions: Record<string, string> = {
          '星空冒险': '浩瀚星空',
          '魔法森林': '神秘森林',
          '友谊成长': '美丽草原',
          '海底寻宝': '湛蓝海洋',
          '勇敢挑战': '险峻山脉'
        };
        
        const emotionSuggestions: Record<string, string> = {
          '星空冒险': '惊喜',
          '魔法森林': '奇幻',
          '友谊成长': '温暖',
          '海底寻宝': '兴奋',
          '勇敢挑战': '勇敢'
        };
        
        const recommendedSetting = settingSuggestions[selectedTheme.name] || '美丽的地方';
        const recommendedEmotion = emotionSuggestions[selectedTheme.name] || '快乐';
        
        suggestions.push(`推荐场景: ${recommendedSetting}`);
        suggestions.push(`推荐情感: ${recommendedEmotion}`);
      }
      
      setAISuggestions(suggestions);
      setIsLoadingSuggestions(false);
    }, 800);
  };
  
  // 处理生成故事
  const handleGenerateStory = async () => {
    if (!selectedCharacter && !selectedTheme && !customPrompt) {
      toast('请至少选择一个角色、主题或输入自定义想法');
      return;
    }
    
    // 设置生成状态
    setIsGenerating(true);
    setGeneratedStory(null);
    setAiProcessStep('正在分析故事元素...');
    
    try {
      // 构建故事生成配置
      const config: StoryGenerationConfig = {
        character: selectedCharacter,
        theme: selectedTheme,
        setting: selectedSetting?.name,
        emotion: selectedEmotion?.name,
        moral: selectedMoral?.name,
        customPrompt,
        length: selectedLength
      };
      
      // 模拟AI思考过程
      await new Promise(resolve => setTimeout(resolve, 1000));
      setAiProcessStep('正在构建故事框架...');
      
      await new Promise(resolve => setTimeout(resolve, 1000));
      setAiProcessStep('正在丰富故事情节...');
      
     // 调用童话家智能体生成故事（会根据配置决定使用真实API还是模拟模式）
    const story = await generateStoryWithLLM(config);
    setGeneratedStory(story);
    
    // 显示生成模式信息
    const aiMode = getAiMode();
    if (aiMode === 'real' && hasValidApiKey()) {
      toast('使用真实AI大模型生成故事成功！', { icon: <CheckCircle size={16} /> });
    }
      
        // 故事生成成功后，预生成所有页面的图片
        toast('正在为故事预生成所有插图，请稍候...');
        // 标记为使用AI生成的图片
        localStorage.setItem('lastGeneratedWithAI', 'true');
      await preGenerateStoryImages(story);
      
      // 检查故事独特性
      setAiProcessStep('正在检查故事独特性...');
      await new Promise(resolve => setTimeout(resolve, 500));
      
      const uniquenessResult = checkStoryUniqueness(story);
      setUniquenessScore(uniquenessResult.uniquenessScore);
      
      // 显示成功提示
      toast(`故事生成成功！独特性评分：${uniquenessResult.uniquenessScore}分`);
    } catch (error) {
      toast('故事生成失败，请稍后再试');
      console.error('Story generation error:', error);
    } finally {
      setIsGenerating(false);
    }
  };
  
  // 清空选择
  const handleClear = () => {
    setSelectedCharacter(null);
    setSelectedTheme(null);
    setSelectedSetting(null);
    setSelectedEmotion(null);
    setSelectedMoral(null);
    setSelectedLength('medium');
    setCustomPrompt('');
    setGeneratedStory(null);
    setUniquenessScore(null);
  };
  
  // 重新生成故事
  const handleRegenerate = () => {
    setGeneratedStory(null);
    setUniquenessScore(null);
    handleGenerateStory();
  };
  
  // 阅读生成的故事
  const handleReadStory = () => {
    if (generatedStory) {
      // 保存故事到本地存储
      localStorage.setItem('generatedStory', JSON.stringify(generatedStory));
      navigate(`/read/${generatedStory.id}`);
    }
  };
  
  // 获取故事提示词预览
  const getPromptPreview = () => {
    let preview = '';
    
    if (selectedCharacter && selectedTheme && selectedSetting) {
      preview = `${selectedCharacter.name}在${selectedSetting.name}的${selectedTheme.name}故事`;
    } else if (selectedCharacter && selectedTheme) {
      preview = `${selectedCharacter.name}的${selectedTheme.name}故事`;
    } else if (selectedCharacter) {
      preview = `${selectedCharacter.name}的冒险故事`;
    } else if (selectedTheme) {
      preview = `${selectedTheme.name}故事`;
    } else if (customPrompt) {
      preview = customPrompt.length > 30 ? customPrompt.substring(0, 30) + '...' : customPrompt;
    } else {
      preview = '智能童话故事';
    }
    
    return preview;
  };
  
  return (
    <div className="min-h-screen bg-gradient-to-b from-pink-50 to-blue-50 flex flex-col pb-24 text-gray-800">
      <div className="container mx-auto flex-1 flex flex-col">
        <Toaster />
        
        <header className="flex items-center justify-between px-6 py-4">
          <div className="flex items-center space-x-4">
            <div className="flex items-center">
              <Brain className="text-pink-400 mr-1" size={18} />
              <span className={`text-sm ${isDark ? 'text-pink-300' : 'text-pink-500'}`}>故事创作魔法</span>
            </div>
           <button 
            onClick={toggleDarkMode}
            className={`p-2 ${isDark ? 'bg-gray-700 text-yellow-400' : 'bg-gradient-to-r from-pink-100 to-blue-100 text-pink-400'} rounded-full hover:from-pink-200 hover:to-blue-200 transition-colors focus:outline-none focus:ring-2 focus:ring-pink-400 focus:ring-offset-2 focus:ring-offset-white dark:focus:ring-offset-gray-800`}
            title={isDark ? "切换到亮色模式" : "切换到护眼模式"}
          >
            {isDark ? <Sun size={18} /> : <Moon size={18} />}
          </button>
          </div>
        </header>

       {/* 页面标题 - 强调智能体共创 */}
      <section className="px-6 pt-6 pb-4">
        <h1 className="text-2xl md:text-3xl font-bold text-gradient flex items-center">
            <img 
              src="https://lf-code-agent.coze.cn/obj/x-ai-cn/307173148162/attachment/e7cb1a9e560c13e8924d04f1d807bc45_20251022234653.jpg" 
              alt="童话家" 
              className="w-10 h-10 rounded-full object-cover mr-3" 
            /> 
          和童话家一起创作故事
        </h1>
        <p className="text-gray-600 mt-2 text-lg">
          告诉我你想创作什么样的故事，童话家会帮你一起构思！
        </p>
      </section>

       {/* 创作引导卡片 - 对话式引导 */}
      <section className="px-6 mb-8">
        <div className="bg-gradient-to-r from-pink-100 to-blue-100 p-4 rounded-xl border border-pink-200 shadow-sm">
          <div className="flex items-start">
            <div className="text-2xl mr-3 mt-1">🧙</div>
            <div>
              <p className="text-pink-600 font-medium">太好了！今天我们故事的主人公想选什么呢？</p>
              <p className="text-pink-600 font-medium mt-1">是一只勇敢的小狮子，还是一艘好奇的宇宙飞船？</p>
              <p className="text-pink-600 mt-3 flex items-center">
                <span className="bg-white text-pink-500 text-xs px-2 py-1 rounded-full mr-2 border border-pink-200">对话创作</span>
                <span className="bg-white text-pink-500 text-xs px-2 py-1 rounded-full mr-2 border border-pink-200">多轮引导</span>
                <span className="bg-white text-pink-500 text-xs px-2 py-1 rounded-full border border-pink-200">智能生成</span>
              </p>
            </div>
          </div>
        </div>
      </section>

       {/* 故事共创区域 - 对话式选择 */}
      <section className="px-6 mb-8">
        <h2 className="text-xl font-semibold text-gray-800 mb-4 flex items-center">
          <Brain className="mr-2 text-pink-400" size={20} />
          和童话家一起构思故事
        </h2>
          
          {/* 选择主人公 - 更大的卡片更适合儿童点击 */}
          <div className="mb-6">
            <h3 className="text-lg font-medium text-pink-500 mb-3 flex items-center">
              <span className="mr-2">👑</span> 选择你的主人公
            </h3>
            <div className="grid grid-cols-4 sm:grid-cols-5 md:grid-cols-6 gap-3">
              {characters.map(character => (
                <div
                  key={character.id}
                  className={`flex flex-col items-center p-3 rounded-lg border cursor-pointer transition-all duration-300 transform hover:scale-105 ${
                    selectedCharacter?.id === character.id 
                      ? 'border-pink-400 bg-gradient-to-br from-pink-100 to-blue-100 shadow-md' 
                      : 'border-gray-200 bg-white hover:border-pink-300 hover:shadow-sm'
                  }`}
                  onClick={() => setSelectedCharacter(character)}
                  title={`选择${character.name}作为主人公`}
                >
                  <span className="text-2xl mb-1">{character.icon}</span>
                  <span className="text-sm text-gray-700">{character.name}</span>
                </div>
              ))}
            </div>
          </div>
          
          {/* 选择主题 */}
          <div className="mb-6">
            <h3 className="text-lg font-medium text-pink-500 mb-3 flex items-center">
              <span className="mr-2">📖</span> 选择故事主题
            </h3>
            <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-3">
              {themes.map(theme => (
                <div
                  key={theme.id}
                  className={`flex flex-col p-3 rounded-lg border cursor-pointer transition-all duration-300 transform hover:scale-105 ${
                    selectedTheme?.id === theme.id 
                      ? 'border-pink-400 bg-gradient-to-br from-pink-100 to-blue-100 shadow-md' 
                      : 'border-gray-200 bg-white hover:border-pink-300 hover:shadow-sm'
                  }`}
                  onClick={() => setSelectedTheme(theme)}
                  title={theme.description}
                >
                  <div className="flex items-center mb-1">
                    <span className="text-lg mr-2 text-pink-400">{theme.icon}</span>
                    <span className="text-sm font-medium text-gray-700">{theme.name}</span>
                  </div>
                  <span className="text-xs text-gray-500">{theme.description}</span>
                </div>
              ))}
            </div>
          </div>
          
          {/* 更多故事元素 */}
          <div className="grid grid-cols-1 md:grid-cols-3 gap-6 mb-6">
            {/* 选择场景 */}
            <div>
              <h3 className="text-lg font-medium text-pink-500 mb-3 flex items-center">
                <span className="mr-2">🏞️</span> 故事发生在哪里？
              </h3>
              <div className="grid grid-cols-4 gap-2">
                {settings.map(setting => (
                  <div
                    key={setting.id}
                    className={`flex flex-col items-center p-2 rounded-lg border cursor-pointer transition-all duration-300 transform hover:scale-105 ${
                      selectedSetting?.id === setting.id 
                        ? 'border-pink-400 bg-gradient-to-br from-pink-100 to-blue-100 shadow-md' 
                        : 'border-gray-200 bg-white hover:border-pink-300'
                    }`}
                    onClick={() => setSelectedSetting(setting)}
                    title={`故事发生在${setting.name}`}
                  >
                    <span className="text-xl mb-1">{setting.icon}</span>
                    <span className="text-xs text-gray-700">{setting.name}</span>
                  </div>
                ))}
              </div>
            </div>
            
            {/* 选择情感 */}
            <div>
              <h3 className="text-lg font-medium text-pink-500 mb-3 flex items-center">
                <span className="mr-2">❤️</span> 故事的心情是？
              </h3>
              <div className="grid grid-cols-4 gap-2">
                {emotions.map(emotion => (
                  <div
                    key={emotion.id}
                    className={`flex flex-col items-center p-2 rounded-lg border cursor-pointer transition-all duration-300 transform hover:scale-105 ${
                      selectedEmotion?.id === emotion.id 
                        ? 'border-pink-400 bg-gradient-to-br from-pink-100 to-blue-100 shadow-md' 
                        : 'border-gray-200 bg-white hover:border-pink-300'
                    }`}
                    onClick={() => setSelectedEmotion(emotion)}
                    title={`故事的心情是${emotion.name}`}
                  >
                    <span className="text-xl mb-1">{emotion.icon}</span>
                    <span className="text-xs text-gray-700">{emotion.name}</span>
                  </div>
                ))}
              </div>
            </div>
            
            {/* 选择道德寓意 */}
            <div>
              <h3 className="text-lg font-medium text-pink-500 mb-3 flex items-center">
                <span className="mr-2">🌟</span> 故事告诉我们？
              </h3>
              <div className="grid grid-cols-4 gap-2">
                {morals.map(moral => (
                  <div
                    key={moral.id}
                    className={`flex flex-col items-center p-2 rounded-lg border cursor-pointer transition-all duration-300 transform hover:scale-105 ${
                      selectedMoral?.id === moral.id 
                        ? 'border-pink-400 bg-gradient-to-br from-pink-100 to-blue-100 shadow-md' 
                        : 'border-gray-200 bg-white hover:border-pink-300'
                    }`}
                    onClick={() => setSelectedMoral(moral)}
                    title={`故事告诉我们${moral.name}`}
                  >
                    <span className="text-xl mb-1">{moral.icon}</span>
                    <span className="text-xs text-gray-700">{moral.name}</span>
                  </div>
                ))}
              </div>
            </div>
          </div>
          
          {/* 选择故事长度 */}
          <div className="mb-6">
            <h3 className="text-lg font-medium text-pink-500 mb-3 flex items-center">
              <Clock className="mr-2" size={18} /> 故事有多长？
            </h3>
            <div className="flex space-x-3">
              {lengths.map(length => (
                <button
                  key={length.id}
                  className={`px-4 py-2 rounded-lg border transition-all duration-300 flex-1 transform hover:scale-105 ${
                    selectedLength === length.id 
                      ? 'border-pink-400 bg-gradient-to-br from-pink-100 to-blue-100 text-pink-500 shadow-sm' 
                      : 'border-gray-200 bg-white text-gray-700 hover:border-pink-300'
                  }`}
                  onClick={() => setSelectedLength(length.id as 'short' | 'medium' | 'long')}
                  title={length.name}
                >
                  {length.name}
                </button>
              ))}
            </div>
          </div>
        </section>

        {/* 自定义故事提示 */}
        <section className="px-6 mb-8">
          <h2 className="text-xl font-semibold text-gray-800 mb-4 flex items-center">
            <Target className="mr-2 text-pink-400" size={20} />
            你的故事想法
          </h2>
          
          <div className="bg-white p-4 rounded-xl border-2 border-pink-100 shadow-md">
            {/* 故事提示预览 */}
            {(selectedCharacter || selectedTheme || selectedSetting || customPrompt) && (
              <div className="mb-4 p-3 bg-gradient-to-r from-pink-50 to-blue-50 rounded-lg border border-pink-100">
                <h3 className="text-sm font-medium text-pink-500 mb-2 flex items-center">
                  <Sparkles size={14} className="mr-1" />
                  故事魔法预览
                </h3>
                <p className="text-gradient font-medium">{getPromptPreview()}</p>
                {selectedMoral && (
                  <p className="text-sm text-pink-500 mt-1">教育意义：{selectedMoral.name}</p>
                )}
              </div>
            )}
            
             {/* 自定义输入框 */}
             <div className="mb-4">
               <label className="text-sm text-gray-600 block mb-2">
                 告诉我们更多想法（可选）：你想让故事里发生什么有趣的事情？
               </label>
               <textarea
                 value={customPrompt}
                 onChange={(e) => setCustomPrompt(e.target.value)}
                 placeholder="例如：勇敢的小狐狸在魔法森林里和朋友们一起寻找彩虹宝石，他们互相帮助，最终找到了宝藏并懂得了友谊的珍贵..."
                 className="w-full px-4 py-3 bg-white border-2 border-pink-100 rounded-lg focus:outline-none focus:ring-2 focus:ring-pink-400 h-36 resize-none text-gray-700"
                 title="输入你对故事的想法"
               />
             </div>
             
             {/* 亲子创作提示 */}
             <div className="mb-4 p-3 bg-pink-50 rounded-lg border border-pink-100">
               <h4 className="text-xs font-medium text-pink-500 mb-2 flex items-center">
                 <span className="mr-1">👨‍👩‍👧‍👦</span>
                 亲子创作提示
               </h4>
               <p className="text-xs text-gray-600">
                 可以和孩子一起讨论故事的情节和角色，鼓励孩子说出自己的想法，这能培养孩子的想象力和表达能力！
               </p>
             </div>
             
             {/* AI智能建议 */}
             {(aiSuggestions.length > 0 || isLoadingSuggestions) && (
               <div className="mb-4 p-3 bg-gradient-to-r from-pink-50 to-blue-50 rounded-lg border border-pink-100">
                 <h3 className="text-sm font-medium text-pink-500 mb-2 flex items-center">
                   <Brain size={14} className="mr-1" />
                   魔法助手的建议
                 </h3>
                 {isLoadingSuggestions ? (
                   <div className="animate-pulse">
                     <div className="h-4 bg-pink-100 rounded w-3/4 mb-1"></div>
                     <div className="h-4 bg-pink-100 rounded w-1/2"></div>
                   </div>
                 ) : (
                   <ul className="text-sm text-gray-700 space-y-1">
                     {aiSuggestions.map((suggestion, index) => (
                       <li key={index} className="flex items-start">
                         <span className="text-pink-400 mr-2">✨</span>
                         {suggestion}
                       </li>
                     ))}
                   </ul>
                 )}
               </div>
             )}
             
             {/* AI生成状态显示 */}
             {isGenerating && (
               <div className="mb-4 p-3 bg-gradient-to-r from-pink-50 to-blue-50 rounded-lg border border-pink-100 flex items-center">
                 <div className="animate-spin mr-3 text-pink-400">
                   <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                     <path d="M12 3v3a6 6 0 0 1 6 6v12" />
                   </svg>
                 </div>
                 <p className="text-pink-500">{aiProcessStep}</p>
               </div>
             )}
             
             {/* 操作按钮 - 更大更醒目 */}
             <div className="flex space-x-3 flex-wrap">
               <button
                 onClick={handleGenerateStory}
                 disabled={isGenerating}
                 className={`flex-1 bg-gradient-to-r from-pink-500 to-blue-500 text-white font-medium py-3 px-4 rounded-lg hover:opacity-90 transition-all duration-300 flex items-center justify-center btn-gradient shadow-md transform hover:scale-105 ${
                   isGenerating ? 'opacity-70 cursor-not-allowed' : ''
                 }`}
                 title="施展创作魔法"
               >
                 <Sparkles size={20} className="mr-2" /> {isGenerating ? '魔法生效中...' : '施展创作魔法'}
               </button>
               <button
                 onClick={handleClear}
                 disabled={isGenerating}
                 className={`px-4 py-3 bg-gradient-to-r from-pink-100 to-blue-100 text-gray-700 font-medium rounded-lg hover:from-pink-200 hover:to-blue-200 transition-colors ${
                   isGenerating ? 'opacity-70 cursor-not-allowed' : ''
                 } shadow-sm`}
                 title="重新选择"
               >
                 重新选择
               </button>
             </div>
           </div>
        </section>

         {/* 智能提示 */}
         <section className="px-6 mb-8">
           <div className="bg-gradient-to-r from-pink-100 to-blue-100 p-4 rounded-xl border border-pink-200 shadow-sm">
             <div className="flex items-center">
               <div className="text-xl mr-3">🧠</div>
               <p className="text-pink-600 font-medium">智能AI会根据你选择的元素，为孩子创造独一无二的童话故事，每个故事都有教育意义和精美插图！</p>
             </div>
           </div>
         </section>
         
         {/* 亲子创作好处 */}
         <section className="px-6 mb-8">
           <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
             <div className="bg-white rounded-xl border border-pink-100 p-4 shadow-sm hover:border-pink-300 hover:shadow-md transition-all duration-300 card-gradient transform hover:-translate-y-1">
               <div className="w-10 h-10 rounded-full bg-gradient-to-r from-pink-100 to-blue-100 flex items-center justify-center text-pink-400 mb-3">
                 <Brain size={20} />
               </div>
               <h3 className="font-semibold text-gray-800 mb-1">培养想象力</h3>
               <p className="text-sm text-gray-600">和孩子一起创作故事，激发孩子的想象力和创造力，让孩子的思维更加活跃。</p>
             </div>
             
             <div className="bg-white rounded-xl border border-pink-100 p-4 shadow-sm hover:border-pink-300 hover:shadow-md transition-all duration-300 card-gradient transform hover:-translate-y-1">
               <div className="w-10 h-10 rounded-full bg-gradient-to-r from-pink-100 to-blue-100 flex items-center justify-center text-pink-400 mb-3">
                 <MessageSquare size={20} />
               </div>
               <h3 className="font-semibold text-gray-800 mb-1">增强表达能力</h3>
               <p className="text-sm text-gray-600">鼓励孩子表达自己的想法，提高语言组织和表达能力，让孩子更加善于沟通。</p>
             </div>
             
             <div className="bg-white rounded-xl border border-pink-100 p-4 shadow-sm hover:border-pink-300 hover:shadow-md transition-all duration-300 card-gradient transform hover:-translate-y-1">
               <div className="w-10 h-10 rounded-full bg-gradient-to-r from-pink-100 to-blue-100 flex items-center justify-center text-pink-400 mb-3">
                 <Heart size={20} />
               </div>
               <h3 className="font-semibold text-gray-800 mb-1">增进亲子感情</h3>
               <p className="text-sm text-gray-600">共同创作的过程中，家长和孩子可以更好地了解彼此，增进亲子之间的感情。</p>
             </div>
           </div>
         </section>
      
        {/* 故事生成结果展示 */}
        {generatedStory && (
          <>
            <section className="px-6 mb-8">
              <div className="bg-white p-5 rounded-xl border-2 border-pink-100 shadow-md bg-gradient-to-br from-pink-50 to-blue-50">
                <div className="flex flex-col sm:flex-row sm:justify-between items-start sm:items-start mb-4">
                  <div>
                    <h2 className="text-xl font-bold text-gradient">{generatedStory.title}</h2>
                    <div className="flex items-center mt-2 flex-wrap gap-2">
                      <div className="bg-pink-100 text-pink-500 text-xs px-2 py-1 rounded-full flex items-center">
                        <CheckCircle size={12} className="mr-1" /> 故事创作完成！
                      </div>
                      <div className="bg-blue-100 text-blue-500 text-xs px-2 py-1 rounded-full flex items-center">
                        <Layers size={12} className="mr-1" /> {generatedStory.pageCount}页精彩内容
                      </div>
                    </div>
                  </div>
                  <div className="mt-3 sm:mt-0 flex items-center bg-gradient-to-r from-pink-100 to-blue-100 px-3 py-1.5 rounded-lg shadow-sm">
                    <Sparkles size={16} className="text-yellow-500 mr-1" />
                    <span className="text-pink-500 font-medium">故事独特性</span>
                    <span className="text-gray-800 font-bold ml-2">{uniquenessScore}%</span>
                  </div>
                </div>
                
                <p className="text-gray-700 mb-4">{generatedStory.description}</p>
                
                <div className="flex flex-wrap gap-2 mb-4">
                  {generatedStory.keywords.map((keyword, index) => (
                    <span key={index} className="bg-pink-50 text-pink-500 text-xs px-2 py-1 rounded-full border border-pink-100">
                      {keyword}
                    </span>
                  ))}
                </div>
                
                <div className="bg-gradient-to-r from-pink-50 to-blue-50 p-3 rounded-lg border border-pink-100 mb-4">
                  <p className="text-sm text-pink-500 flex items-center">
                    <Heart size={14} className="mr-2" /> 教育意义：{generatedStory.moral}
                  </p>
                </div>
                
                <div className="flex space-x-3 flex-wrap">
                  <button
                    onClick={handleReadStory}
                    className="flex-1 bg-gradient-to-r from-pink-500 to-blue-500 text-white font-medium py-3 px-4 rounded-lg hover:opacity-90 transition-all duration-300 flex items-center justify-center btn-gradient shadow-md"
                    title="开始阅读故事"
                  >
                    <MessageSquare size={20} className="mr-2" /> 开始阅读故事
                  </button>
                  <button
                    onClick={handleRegenerate}
                    className="px-4 py-3 bg-gradient-to-r from-pink-100 to-blue-100 text-gray-700 font-medium rounded-lg hover:from-pink-200 hover:to-blue-200 transition-colors flex items-center shadow-sm"
                    title="重新创作故事"
                  >
                    <RefreshCw size={20} className="mr-2" /> 重新创作
                  </button>
                </div>
              </div>
            </section>
            
            {/* 收藏生成故事的按钮 */}
            <div className="px-6 mb-8">
            <button
              onClick={() => {
                try {
                  // 获取已有的收藏列表
                  const collections = localStorage.getItem('collectedStories');
                  let parsedCollections: { id: string; title: string; description: string; pageCount: number; date: string }[] = [];
                  
                  if (collections) {
                    parsedCollections = JSON.parse(collections);
                  }
                  
                  // 检查故事是否已在收藏中
                  const isAlreadyCollected = parsedCollections.some(story => story.id === generatedStory.id);
                  
                  if (!isAlreadyCollected) {
                    // 添加到收藏
                    const newCollection = {
                      id: generatedStory.id,
                      title: generatedStory.title,
                      description: generatedStory.description,
                      pageCount: generatedStory.pageCount,
                      date: new Date().toLocaleDateString('zh-CN')
                    };
                    parsedCollections.push(newCollection);
                    toast('故事已添加到收藏！');
                    
                    // 保存回localStorage前确保数据唯一
                    const uniqueCollections = Array.from(new Map(parsedCollections.map(story => [story.id, story])).values());
                    localStorage.setItem('collectedStories', JSON.stringify(uniqueCollections));
                  } else {
                    toast('故事已在收藏中');
                  }
                } catch (error) {
                  console.error('Failed to add to collection:', error);
                  toast('收藏失败，请稍后再试');
                }
              }}
                className="w-full bg-gradient-to-r from-pink-500 to-blue-500 text-white font-medium py-3 px-4 rounded-lg hover:opacity-90 transition-all duration-300 flex items-center justify-center btn-gradient shadow-md"
                title="添加到收藏"
              >
                <Heart size={20} className="mr-2" /> 添加到我的收藏
              </button>
            </div>
          </>
        )}

        {/* API配置和测试按钮 */}
      <div className="fixed bottom-24 right-4 z-30 flex flex-col items-end gap-3">
        <button
          onClick={() => {
            // 直接测试API连接
            const apiKey = getApiKey();
            if (!apiKey) {
              toast('请先配置API Key');
              setIsApiConfigOpen(true);
              return;
            }
            
            // 显示加载状态
            toast('正在测试API连接...');
            
            // 执行测试
            const testApiConnection = async () => {
              try {
                const response = await fetch('https://open.bigmodel.cn/api/paas/v4/chat/completions', {
                  method: 'POST',
                  headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${apiKey}`
                  },
         body: JSON.stringify({
                    model: 'glm-4',
                    messages: [{ role: 'user', content: '你好' }],
                    max_tokens: 50,
                    temperature: 0.7
                  })
                });
                
                if (response.ok) {
                  const data = await response.json();
                  if (data.choices && data.choices.length > 0) {
                    toast('API连接成功！您的配置生效了', { icon: <CheckCircle size={16} /> });
                  } else {
                    toast('API返回异常，请检查API Key是否正确', { icon: <AlertCircle size={16} /> });
                  }
                } else {
                  const errorData = await response.json();
                  toast(`API连接失败: ${errorData.error?.message || '未知错误'}`, { icon: <AlertCircle size={16} /> });
                }
              } catch (error) {
                toast('网络连接失败，请检查您的网络设置', { icon: <AlertCircle size={16} /> });
                console.error('API test failed:', error);
              }
            };
            
            testApiConnection();
          }}
          className="w-12 h-12 rounded-full bg-gradient-to-r from-green-500 to-blue-500 flex items-center justify-center shadow-lg hover:shadow-xl transition-all duration-300 transform hover:scale-110"
          title="测试API连接"
        >
          <span className="text-2xl">🧪</span>
        </button>
        
        <button
          onClick={() => setIsApiConfigOpen(true)}
          className="w-12 h-12 rounded-full bg-gradient-to-r from-pink-500 to-blue-500 flex items-center justify-center shadow-lg hover:shadow-xl transition-all duration-300 transform hover:scale-110"
          title="配置智谱AI API"
        >
          <span className="text-2xl">⚙️</span>
        </button>
      </div>
      
      {/* API配置模态框 */}
      <ApiConfigModal 
        isOpen={isApiConfigOpen} 
        onClose={() => setIsApiConfigOpen(false)} 
      />
      
      {/* 底部导航栏 - 更大更醒目 */}
        <nav className="fixed bottom-0 left-0 right-0 bg-white/95 backdrop-blur-md border-t-2 border-pink-200 h-20 flex justify-around items-center z-10 shadow-md">
          <Link to="/home" className="flex flex-col items-center justify-center text-gray-500 hover:text-pink-500 transition-colors">
            <span className="text-2xl">🏠</span>
            <span className="text-sm mt-1 font-medium">首页</span>
          </Link>
          <Link to="/generate" className="flex flex-col items-center justify-center text-pink-500">
            <span className="text-2xl">✨</span>
            <span className="text-sm mt-1 font-medium">创作</span>
          </Link>
          <Link to="/collection" className="flex flex-col items-center justify-center text-gray-500 hover:text-pink-500 transition-colors">
            <span className="text-2xl">❤️</span>
            <span className="text-sm mt-1 font-medium">收藏</span>
          </Link>
          <Link to="/agent" className="flex flex-col items-center justify-center text-gray-500 hover:text-pink-500 transition-colors">
            <span className="text-2xl">🤖</span>
            <span className="text-sm mt-1 font-medium">助手</span>
          </Link>
        </nav>
      </div>
    </div>
  );
}